import { CNY } from '@/constants/global'
import { SET_FUND_DATA } from '@/constants/mutation-types'
import * as API from '@/constants/api'

export const state = () => ({
  totalMoney: 0, // 总资产(usd)
  ownedCoins: {}
})

export const getters = {
  calcTotalMoney (state, _, { currency, market }) {
    if (currency.name === CNY) {
      return state.totalMoney * market.usd2cny
    }
    return state.totalMoney
  },
  getCoinBalance: state => (coin) => {
    return state.ownedCoins[coin]
  }
}

export const mutations = {
  [SET_FUND_DATA] (state, data) {
    state.totalMoney = data.total_money
    const ownedCoins = {}
    data.list.forEach((item) => {
      ownedCoins[item.name] = item
    })
    state.ownedCoins = { ...state.ownedCoins, ...ownedCoins }
  }
}

export const actions = {
  async getExchangeBalance ({ commit }, params) {
    const { data } = await this.$axios.$post(API.GET_EXCHANGE_BALANCE, params)
    commit(SET_FUND_DATA, data)
    return data
  },
  // 生成充值地址
  async withdrawGenerateAddress ({ commit }, params) {
    return await this.$axios.$post(API.GENERATE_WITHDRAW_ADDRESS, params)
  },
  // 获取提币限制条件
  async bankWithdrawPrepare ({ commit }, params) {
    return await this.$axios.$post(API.GET_WITHDRAW_RESTRICTIONS, params)
  },
  // 申请提币
  async withdrawTurnOut ({ commit }, params) {
    return await this.$axios.$post(API.APPLY_WITHDRAW, params)
  }
}
